package com.print;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashAttributeSet;
import javax.print.attribute.standard.PrinterName;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class PrintDJ {
	private String modelTyp;//打印模板
	private Integer loop;
	private Boolean imgFlg;//是否打印表头图片

	public String getModelTyp() {
		return modelTyp;
	}
	public void setModelTyp(String modelTyp) {
		this.modelTyp = modelTyp;
	}
	public Integer getLoop() {
		return loop;
	}
	public void setLoop(Integer loop) {
		this.loop = loop;
	}
	public Boolean getImgFlg() {
		return imgFlg;
	}
	public void setImgFlg(Boolean imgFlg) {
		this.imgFlg = imgFlg;
	}
	public PrintDJ(String modelTyp,Integer loop,Boolean imgFlg){
		this.modelTyp = modelTyp;
		this.loop = loop;
		this.imgFlg = imgFlg;
	}
	/**
	 * 新建Workbook
	 * @throws IOException 
	 */
	public HSSFWorkbook creatWorkbook() throws IOException{
		
		InputStream in = null;
		if(modelTyp.equals("1")){//for 减薄镀膜产品出货检验单
			in = LabelAppletComm.class.getResourceAsStream("/com/excel/dj/DJ.xls");
		}else if(modelTyp.equals("2")){//for 产品信息记录表
			in = LabelAppletComm.class.getResourceAsStream("/com/excel/dj/DJ02.xls");
		}
		
		HSSFWorkbook workbook = new HSSFWorkbook(in);
		
		for (int i = 0; i < loop; i++) {
			HSSFSheet newsheet = null;
			HSSFSheet fromsheet = workbook.getSheetAt(0);
			newsheet = workbook
			.createSheet("sheet" + (String.valueOf(i + 1)));
			copyRows(workbook, fromsheet, newsheet, fromsheet.getFirstRowNum(), fromsheet.getLastRowNum());
	        //设置工作簿缩放比例  ,"缩放"设置中，将所有列调整为一列
			newsheet.setAutobreaks(true); 
	        //设定边距
            newsheet.setMargin(HSSFSheet.TopMargin,fromsheet.getMargin(HSSFSheet.TopMargin));// 页边距（上）    
            newsheet.setMargin(HSSFSheet.BottomMargin,fromsheet.getMargin(HSSFSheet.BottomMargin));// 页边距（下）    
            newsheet.setMargin(HSSFSheet.LeftMargin,fromsheet.getMargin(HSSFSheet.LeftMargin) );// 页边距（左）    
            newsheet.setMargin(HSSFSheet.RightMargin,fromsheet.getMargin(HSSFSheet.RightMargin));// 页边距（右 ）
			newsheet.setHorizontallyCenter(true); //设置打印页面为水平居中
			if(modelTyp.equals("1") || modelTyp.equals("3")){
				newsheet.setVerticallyCenter(false); //不设置打印页面为垂直居中
			}else{
				newsheet.setVerticallyCenter(true); //设置打印页面为垂直居中
			}
			
	        HSSFPrintSetup printSetup = newsheet.getPrintSetup();
	        //A4纸  
	        printSetup.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE); 
	        //设定横向
	        if(modelTyp.equals("1") || modelTyp.equals("3")){
	        	printSetup.setLandscape(false);
	        }else{
		        printSetup.setLandscape(true); // 打印方向，true：横向，false：纵向(默认) 
	        }
	        printSetup.setFitHeight((short) 1);//设置缩放调整为页高 
	        printSetup.setFitWidth((short) 1);//设置缩放调整为页宽
		}
		
		workbook.removeSheetAt(0);
		in.close();
		
		return workbook;
	}
	/**
	* 复制模板
	* 
	* @param workbook
	* @param fromsheet
	* @param newsheet
	* @param firstrow
	* @param lastrow
	* 
	* copySheet("template", "test2", "d:/template.xls");
	 * @throws IOException 
	*/
	@SuppressWarnings("deprecation")
	public void copyRows(HSSFWorkbook workbook, HSSFSheet fromsheet,
	HSSFSheet newsheet, int firstrow, int lastrow) throws IOException {
		if(imgFlg){
			ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
	        InputStream in = LabelApplet4JX.class.getResourceAsStream("/com/excel/DJN.JPG");
	        BufferedImage bufferImg = ImageIO.read(in);  
			ImageIO.write(bufferImg, "jpg", byteArrayOut); 
			HSSFPatriarch patriarch = newsheet.createDrawingPatriarch();
			 //anchor主要用于设置图片的属性  
	        HSSFClientAnchor anchor = new HSSFClientAnchor(20, 50, 180, 200,(short) 0, 0, (short) 2, 2);     
	        anchor.setAnchorType(3);
	        //插入图片    
	        patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG)).resize(1); 
	        //resize是放大或缩小的函数。用了这个函数后，HSSFClientAnchor构造函数中的图片显示的终了cell位置就不起作用了; 
		}
		if ((firstrow == -1) || (lastrow == -1) || lastrow < firstrow) {
			return;
		}
		// 拷贝合并的单元格
		Region region = null;
		for (int i = 0; i < fromsheet.getNumMergedRegions(); i++) {
			region = fromsheet.getMergedRegionAt(i);
			if ((region.getRowFrom() >= firstrow)
					&& (region.getRowTo() <= lastrow)) {
				newsheet.addMergedRegion(region);
			}
		}
		HSSFRow fromRow = null;
		HSSFRow newRow = null;
		HSSFCell newCell = null;
		HSSFCell fromCell = null;
		// 设置列宽
		for (int i = firstrow; i <= lastrow; i++) {
			fromRow = fromsheet.getRow(i);
			if (fromRow != null) {
				for (int j = fromRow.getLastCellNum(); j >= fromRow.getFirstCellNum(); j--) {
					int colnum = fromsheet.getColumnWidth(j);
					if (colnum > 100) {
						newsheet.setColumnWidth(j,colnum);
					}
					if (colnum == 0) {
						newsheet.setColumnHidden(j,true);
					} else {
						newsheet.setColumnHidden(j,false);
					}
				}
				break;
			}
		}
		// 拷贝行并填充数据
		for (int i = 0; i <= lastrow; i++) {
			fromRow = fromsheet.getRow(i);
			if (fromRow == null) {
				continue;
			}
			newRow = newsheet.createRow(i - firstrow);
			newRow.setHeight(fromRow.getHeight());
			for (int j = fromRow.getFirstCellNum(); j < fromRow.getPhysicalNumberOfCells(); j++) {
				fromCell = fromRow.getCell((short) j);
				if (fromCell == null) {
					continue;
				}
				newCell = newRow.createCell((short) j);
				newCell.setCellStyle(fromCell.getCellStyle());
				int cType = fromCell.getCellType();
				newCell.setCellType(cType);
				switch (cType) {
					case HSSFCell.CELL_TYPE_STRING:
						newCell.setCellValue(fromCell.getRichStringCellValue());
						break;
					case HSSFCell.CELL_TYPE_NUMERIC:
						newCell.setCellValue(fromCell.getNumericCellValue());
						break;
					case HSSFCell.CELL_TYPE_FORMULA:
						newCell.setCellFormula(fromCell.getCellFormula());
						break;
					case HSSFCell.CELL_TYPE_BOOLEAN:
						newCell.setCellValue(fromCell.getBooleanCellValue());
						break;
					case HSSFCell.CELL_TYPE_ERROR:
						newCell.setCellValue(fromCell.getErrorCellValue());
						break;
					default:
						newCell.setCellValue(fromCell.getRichStringCellValue());
						break;
				}
			}
		}
	}
	
	/**
	 * 打印Excel
	 * @param filePath
	 */
	public void printExcel(String printerName,String filePath){
	    ComThread.InitSTA(true);
	    Dispatch excel = null;
	    ActiveXComponent xl = new ActiveXComponent("Excel.Application");
	    HashAttributeSet has = new HashAttributeSet();
        has.add(new PrinterName(printerName, null));
        PrintService[] services = PrintServiceLookup.lookupPrintServices(null, has);

	    try {
	        // 这里Visible是控制文档打开后是可见还是不可见，若是静默打印，那么第三个参数就设为false就好了
	        Dispatch.put(xl, "Visible", new Variant(false));
	        Dispatch workbooks = xl.getProperty("Workbooks").toDispatch();
	        // 打开文档
	        excel = Dispatch.call(workbooks, "Open", filePath)
	                .toDispatch();

	        Dispatch sheets = Dispatch.get((Dispatch) excel, "Sheets")
	        .toDispatch();
	        
	        // 获得几个sheet,并打印
	        int count = Dispatch.get(sheets, "Count").getInt();
	        System.out.println(count);
	        for (int j = 1; j <=count; j++) {
	        	Dispatch sheet = Dispatch.invoke(sheets, "Item",
	        			Dispatch.Get, new Object[] { new Integer(j) },
	        			new int[1]).toDispatch();
	        	Dispatch pageSetup = Dispatch.get(sheet, "PageSetup").toDispatch();
	        	if(modelTyp.equals("1") || modelTyp.equals("3")){
	        		Dispatch.put(pageSetup, "Orientation", new Variant(1));//纵向打印
	        	}else{
		        	Dispatch.put(pageSetup, "Orientation", new Variant(2));//横向打印
	        	}
	        	if(services == null || services.length == 0){
	        		Dispatch.call(sheet, "PrintOut");
	        	}else{
	        		Dispatch.callN(sheet,"PrintOut",new Object[]{Variant.VT_MISSING, Variant.VT_MISSING, 1,//打印一份
							new Boolean(false),printerName, new Boolean(true),Variant.VT_MISSING, ""});
	        	}

	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    } finally {
	        //增加以下三行代码解决文件无法删除bug
//	        Dispatch.call(excel, "save");
	        Dispatch.call(excel,  "Close" ,  new  Variant(false));
	        excel=null;
	        //关闭文档
	        xl.invoke("Quit",new Variant[] {});
	        xl = null;
	        // 始终释放资源
	        ComThread.Release();
	    }
	}
}
